package com.leyou.trade.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.utils.UserContext;
import com.leyou.common.exception.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.trade.dto.OrderFormDTO;
import com.leyou.trade.entity.CartItem;
import com.leyou.trade.entity.Order;
import com.leyou.trade.entity.OrderDetail;
import com.leyou.trade.entity.OrderLogistics;
import com.leyou.trade.entity.enums.OrderStatus;
import com.leyou.trade.mapper.OrderMapper;
import com.leyou.trade.repository.CartItemRepository;
import com.leyou.trade.service.OrderDetailService;
import com.leyou.trade.service.OrderLogisticsService;
import com.leyou.trade.service.OrderService;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.AddressDTO;
import com.mongodb.client.model.Filters;
import feign.FeignException;
import org.apache.commons.lang.StringUtils;
import org.bson.conversions.Bson;
import org.joda.time.DateTimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    private static String CARTS = "carts";

    @Autowired
    private ItemClient itemClient;
    @Autowired
    private UserClient userClient;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderLogisticsService orderLogisticsService;

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    @Transactional
    public Long createOrder(OrderFormDTO orderFormDTO) {
        //1.处理order数据
        Order order = new Order();
        //1.1 处理订单金额相关数据  查询sku 根据sku价格计算总金额 运费 优惠后的实付金额
        //1.1.1 获取订单中的商品基本信息
        Map<Long, Integer> carts = orderFormDTO.getCarts();
        //1.1.2获取sku的id
        Set<Long> skuIds = carts.keySet();
        //1.1.3查询sku
        List<SkuDTO> skuList = itemClient.querySkuDTOListByIds(skuIds);
        //1.1.4 计算总金额
        long total = 0;
        for (SkuDTO sku : skuList) {
            //判断商品是否处于上架状态
            if (!sku.getSaleable()){
                throw new LyException(400,"商品已经下架，无法下单");
            }
            //获取商品的购买数量
            Integer num = carts.get(sku.getId());
            total += sku.getPrice() * num;
        }
        //付款金额
        order.setTotalFee(total);
        //支付类型
        order.setPaymentType(orderFormDTO.getPaymentType());
        //TODO  1.1.5 根据物流计算运费  全场包邮
        order.setPostFee(0L);
        //TODO 1.1.6  优惠   无优惠
        order.setActualFee(total + order.getPostFee());

        //1.2 用户信息
        Long userId = UserContext.getUser().getId();
        order.setUserId(userId);
        //1.3 默认状态
        order.setStatus(OrderStatus.INIT.getValue());
        //1.4 写入数据库
        boolean success = save(order);
        if (!success){
            //订单写入失败
            throw new LyException(500,"订单创建异常");
        }
        //id 回显
        Long orderId = order.getOrderId();

        //2.处理orderDetail
        List<OrderDetail> details = new ArrayList<>(skuIds.size());
        //2.1查询所有sku  转换为orderDetail
        for (SkuDTO skuDTO : skuList) {
            OrderDetail detail = new OrderDetail();
            //写入值
            detail.setTitle(skuDTO.getTitle());
            detail.setSpec(skuDTO.getSpecialSpec());
            detail.setSkuId(skuDTO.getId());
            detail.setPrice(skuDTO.getPrice());
            detail.setOrderId(orderId);
            detail.setNum(carts.get(skuDTO.getId()));
            detail.setImage(StringUtils.substringBefore(skuDTO.getImages(),","));
            //添加到集合
            details.add(detail);
        }
        //2.2批量写入数据
        orderDetailService.saveBatch(details);

        //3.处理OrderLogistics
        //3.1 根据id查询地址信息
        Long addressId = orderFormDTO.getAddressId();
        AddressDTO addressDTO = userClient.queryAddressById(addressId);
        //3.2 查询的地址信息封装到OrderLogistics
        OrderLogistics orderLogistics = addressDTO.toEntity(OrderLogistics.class);
        orderLogistics.setOrderId(orderId);
        //3.3 写入数据库
        success = orderLogisticsService.save(orderLogistics);
        if (!success){
            throw new LyException(500,"订单新增失败！");
        }

        //4 修改库存
        try {
            itemClient.deductStock(carts);
        } catch (FeignException e) {
            throw new LyException(e.status(),e.contentUTF8());
        }

        //5.在购物车中删除提交订单的商品
        for (Long skuId : skuIds) {

            Bson bson = Filters.eq("_id", CartItem.generateId(userId,skuId));
            mongoTemplate.getCollection(CARTS + userId).deleteMany(bson);

/*            mongoTemplate.remove(CartItem.class)
                    .matching(Query.query(Criteria.where("_id").is(CartItem.generateId(userId,skuId))))
                    .all();*/
        }
        return orderId;

    }


}
